package entity;


import database.DatabaseHelper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class Student {

    private String id;
    private String name;
    private String sex;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public Student(String id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    /* C */
    public static boolean create(DatabaseHelper db, String id, String name, String sex) throws SQLException {
        return db.update("insert into student(id,name,sex) value (?,?,?)", id, name, sex) > 0;
    }

    /* R */
    public static ArrayList<Student> findWhere(DatabaseHelper db, String condition, Object... params) throws SQLException {
        String query = "select id, name, sex from student where " + condition;
        ResultSet rs = db.query(query, params);
        ArrayList<Student> students = new ArrayList<>();
        while (rs.next()) {
            students.add(new Student(rs.getString(1), rs.getString(2), rs.getString(3)));
        }
        rs.close();
        return students;
    }

    public static Student find(DatabaseHelper db, String id)  throws SQLException{
        ArrayList<Student> students = findWhere(db, "id = ?", id);
        return students.isEmpty() ? null : students.get(0);
    }

    public static ArrayList<Student> findByName(DatabaseHelper db, String name) throws SQLException{
        return findWhere(db, "name = ?", name);
    }

    public static ArrayList<Student> findAll(DatabaseHelper db)  throws SQLException{
        return findWhere(db, "true");
    }

    public ArrayList<Section> getSections(DatabaseHelper db) throws SQLException {
        return Section.findWhere(db, "id in (select sec_id from take where stu_id = ?)", id);
    }

    public boolean refresh(DatabaseHelper db) throws SQLException {
        Student stu = find(db, id);
        if (stu == null)
            return false;
        name = stu.name;
        sex = stu.sex;
        return true;
    }

    /* U */
    public boolean setAttribute(DatabaseHelper db, String attribute, Object value) throws SQLException {
        String update = "update student set " + attribute + " = ? where id = ?";
        int affectedRows = db.update(update, value, id);
        refresh(db);
        return affectedRows > 0;
    }

    public boolean setName(DatabaseHelper db, String name) throws SQLException {
        return setAttribute(db, "name", name);
    }

    public boolean setSex(DatabaseHelper db, String sex) throws SQLException {
        return setAttribute(db, "sex", sex);
    }

    /* D */
    public boolean delete(DatabaseHelper db) throws SQLException {
        return db.update("delete from student where id = ?", id) > 0;
    }
}
